import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { 
  getCourses, 
  getCourseDetail, 
  getMyCourses, 
  getFavoriteCourses,
  favoriteCourse,
  unfavoriteCourse,
  enrollCourse,
  cancelEnrollment
} from '@/api/course'

export const useCourseStore = defineStore('course', () => {
  // 状态
  const courses = ref([])
  const currentCourse = ref(null)
  const myCourses = ref([])
  const favoriteCourses = ref([])
  const courseCategories = ref([])
  const courseTags = ref([])
  const loading = ref(false)
  const searchKeyword = ref('')
  const filters = ref({
    category: '',
    difficulty: '',
    price: '',
    status: '',
    sort: 'latest'
  })
  const pagination = ref({
    page: 1,
    limit: 12,
    total: 0,
    totalPages: 0
  })

  // 计算属性
  const filteredCourses = computed(() => {
    let result = courses.value
    
    // 关键词搜索
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      result = result.filter(course => 
        course.title.toLowerCase().includes(keyword) ||
        course.description.toLowerCase().includes(keyword) ||
        course.instructor.name.toLowerCase().includes(keyword)
      )
    }
    
    // 分类筛选
    if (filters.value.category) {
      result = result.filter(course => course.category === filters.value.category)
    }
    
    // 难度筛选
    if (filters.value.difficulty) {
      result = result.filter(course => course.difficulty === filters.value.difficulty)
    }
    
    // 价格筛选
    if (filters.value.price) {
      if (filters.value.price === 'free') {
        result = result.filter(course => course.price === 0)
      } else if (filters.value.price === 'paid') {
        result = result.filter(course => course.price > 0)
      }
    }
    
    // 状态筛选
    if (filters.value.status) {
      result = result.filter(course => course.status === filters.value.status)
    }
    
    return result
  })

  const enrolledCourseIds = computed(() => 
    myCourses.value.map(course => course.id)
  )

  const favoriteCourseIds = computed(() => 
    favoriteCourses.value.map(course => course.id)
  )

  // 获取课程列表
  const fetchCourses = async (params = {}) => {
    try {
      loading.value = true
      const queryParams = {
        page: pagination.value.page,
        limit: pagination.value.limit,
        keyword: searchKeyword.value,
        ...filters.value,
        ...params
      }
      
      const response = await getCourses(queryParams)
      const { data, total, page, limit } = response.data
      
      courses.value = data
      pagination.value = {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
      
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取课程详情
  const fetchCourseDetail = async (courseId) => {
    try {
      loading.value = true
      const response = await getCourseDetail(courseId)
      currentCourse.value = response.data
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取我的课程
  const fetchMyCourses = async (params = {}) => {
    try {
      const response = await getMyCourses(params)
      myCourses.value = response.data.data || response.data
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取收藏课程
  const fetchFavoriteCourses = async (params = {}) => {
    try {
      const response = await getFavoriteCourses(params)
      favoriteCourses.value = response.data.data || response.data
      return response
    } catch (error) {
      throw error
    }
  }

  // 收藏课程
  const addToFavorites = async (courseId) => {
    try {
      await favoriteCourse(courseId)
      
      // 更新本地状态
      const course = courses.value.find(c => c.id === courseId)
      if (course && !favoriteCourseIds.value.includes(courseId)) {
        favoriteCourses.value.unshift(course)
      }
      
      // 更新课程的收藏状态
      if (course) {
        course.isFavorited = true
        course.favoriteCount = (course.favoriteCount || 0) + 1
      }
      
      if (currentCourse.value && currentCourse.value.id === courseId) {
        currentCourse.value.isFavorited = true
        currentCourse.value.favoriteCount = (currentCourse.value.favoriteCount || 0) + 1
      }
    } catch (error) {
      throw error
    }
  }

  // 取消收藏
  const removeFromFavorites = async (courseId) => {
    try {
      await unfavoriteCourse(courseId)
      
      // 更新本地状态
      const index = favoriteCourses.value.findIndex(c => c.id === courseId)
      if (index > -1) {
        favoriteCourses.value.splice(index, 1)
      }
      
      // 更新课程的收藏状态
      const course = courses.value.find(c => c.id === courseId)
      if (course) {
        course.isFavorited = false
        course.favoriteCount = Math.max((course.favoriteCount || 1) - 1, 0)
      }
      
      if (currentCourse.value && currentCourse.value.id === courseId) {
        currentCourse.value.isFavorited = false
        currentCourse.value.favoriteCount = Math.max((currentCourse.value.favoriteCount || 1) - 1, 0)
      }
    } catch (error) {
      throw error
    }
  }

  // 报名课程
  const enrollInCourse = async (courseId) => {
    try {
      await enrollCourse(courseId)
      
      // 更新本地状态
      const course = courses.value.find(c => c.id === courseId)
      if (course && !enrolledCourseIds.value.includes(courseId)) {
        myCourses.value.unshift({
          ...course,
          enrolledAt: new Date(),
          progress: 0
        })
      }
      
      // 更新课程的报名状态
      if (course) {
        course.isEnrolled = true
        course.enrollmentCount = (course.enrollmentCount || 0) + 1
      }
      
      if (currentCourse.value && currentCourse.value.id === courseId) {
        currentCourse.value.isEnrolled = true
        currentCourse.value.enrollmentCount = (currentCourse.value.enrollmentCount || 0) + 1
      }
    } catch (error) {
      throw error
    }
  }

  // 取消报名
  const cancelCourseEnrollment = async (courseId) => {
    try {
      await cancelEnrollment(courseId)
      
      // 更新本地状态
      const index = myCourses.value.findIndex(c => c.id === courseId)
      if (index > -1) {
        myCourses.value.splice(index, 1)
      }
      
      // 更新课程的报名状态
      const course = courses.value.find(c => c.id === courseId)
      if (course) {
        course.isEnrolled = false
        course.enrollmentCount = Math.max((course.enrollmentCount || 1) - 1, 0)
      }
      
      if (currentCourse.value && currentCourse.value.id === courseId) {
        currentCourse.value.isEnrolled = false
        currentCourse.value.enrollmentCount = Math.max((currentCourse.value.enrollmentCount || 1) - 1, 0)
      }
    } catch (error) {
      throw error
    }
  }

  // 设置搜索关键词
  const setSearchKeyword = (keyword) => {
    searchKeyword.value = keyword
  }

  // 设置筛选条件
  const setFilters = (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
  }

  // 重置筛选条件
  const resetFilters = () => {
    filters.value = {
      category: '',
      difficulty: '',
      price: '',
      status: '',
      sort: 'latest'
    }
    searchKeyword.value = ''
  }

  // 设置分页
  const setPagination = (page, limit) => {
    pagination.value.page = page
    if (limit) {
      pagination.value.limit = limit
    }
  }

  // 下一页
  const nextPage = () => {
    if (pagination.value.page < pagination.value.totalPages) {
      pagination.value.page++
    }
  }

  // 上一页
  const prevPage = () => {
    if (pagination.value.page > 1) {
      pagination.value.page--
    }
  }

  // 检查课程是否已收藏
  const isCourseInFavorites = (courseId) => {
    return favoriteCourseIds.value.includes(courseId)
  }

  // 检查课程是否已报名
  const isCourseEnrolled = (courseId) => {
    return enrolledCourseIds.value.includes(courseId)
  }

  // 获取课程进度
  const getCourseProgress = (courseId) => {
    const course = myCourses.value.find(c => c.id === courseId)
    return course ? course.progress || 0 : 0
  }

  // 更新课程进度
  const updateCourseProgress = (courseId, progress) => {
    const course = myCourses.value.find(c => c.id === courseId)
    if (course) {
      course.progress = progress
      course.lastStudiedAt = new Date()
    }
  }

  // 清除当前课程
  const clearCurrentCourse = () => {
    currentCourse.value = null
  }

  // 重置状态
  const resetState = () => {
    courses.value = []
    currentCourse.value = null
    myCourses.value = []
    favoriteCourses.value = []
    courseCategories.value = []
    courseTags.value = []
    loading.value = false
    searchKeyword.value = ''
    resetFilters()
    pagination.value = {
      page: 1,
      limit: 12,
      total: 0,
      totalPages: 0
    }
  }

  return {
    // 状态
    courses,
    currentCourse,
    myCourses,
    favoriteCourses,
    courseCategories,
    courseTags,
    loading,
    searchKeyword,
    filters,
    pagination,
    
    // 计算属性
    filteredCourses,
    enrolledCourseIds,
    favoriteCourseIds,
    
    // 方法
    fetchCourses,
    fetchCourseDetail,
    fetchMyCourses,
    fetchFavoriteCourses,
    addToFavorites,
    removeFromFavorites,
    enrollInCourse,
    cancelCourseEnrollment,
    setSearchKeyword,
    setFilters,
    resetFilters,
    setPagination,
    nextPage,
    prevPage,
    isCourseInFavorites,
    isCourseEnrolled,
    getCourseProgress,
    updateCourseProgress,
    clearCurrentCourse,
    resetState
  }
}, {
  persist: {
    key: 'course-store',
    storage: localStorage,
    paths: ['myCourses', 'favoriteCourses']
  }
})